package com.music.mysongs.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.view.KeyEvent
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.annotation.RequiresApi
import com.music.mysongs.R
import com.music.mysongs.fragment.option.SongMsgFragment
import com.music.mysongs.helper.getTimeFormat
import com.music.mysongs.service.MusicService
import com.music.mysongs.utils.BaseActivity
import com.music.mysongs.utils.myLog
import kotlinx.android.synthetic.main.activity_song.*

class SongActivity : BaseActivity(), View.OnClickListener {
    private val mTAG = "SongActivity"
    private var sorts: String? = null//web/love/local/collect
    private var index: Int? = null
    private var muBinder: MusicService.MusicBinder? = null

    private val muConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            myLog("$mTAG: onServiceConnected")
            muBinder = service as MusicService.MusicBinder
            //传给service进度
            seekBar_song.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
                override fun onProgressChanged(
                    seekBar: SeekBar,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    if (fromUser) {
                        muBinder!!.setSeekTo(progress)
                    }
                }

                override fun onStartTrackingTouch(seekBar: SeekBar) {}
                override fun onStopTrackingTouch(seekBar: SeekBar) {}
            })
            myHandler.post(myRunnable)
        }

        override fun onServiceDisconnected(name: ComponentName) {
            myLog("$mTAG: onServiceDisconnected")
        }
    }

    //接收service更新
    var myHandler = Handler()
    var myRunnable: Runnable = object : Runnable {
        override fun run() {
            muBinder?.let { muBinder ->
                //更新UI
                txtDuration_song.text = getTimeFormat(muBinder.setDuration())
                txtCurrent_song.text = getTimeFormat(muBinder.setCurrent())
                seekBar_song.progress = muBinder.setCurrent()
                seekBar_song.max = muBinder.setDuration()
                this@SongActivity.topBar_song.setTitle(muBinder.setName(), muBinder.setArtist())
                //seekBar_song.secondaryProgress = muBinder.setSecSeek()
                //更新播放
                if (muBinder.setIsPlay()) {
                    btnPlayOrPause_song.setBackgroundResource(R.drawable.ic_song_play_128)
                } else {
                    btnPlayOrPause_song.setBackgroundResource(R.drawable.ic_song_pause_128)
                }
                //更新喜欢
                if (sorts != "db_local" && sorts != null) {
                    btnLove_song.visibility = View.VISIBLE
                    //layoutFra_song.onHiddenChanged(true)
                    if (muBinder.setIsLike()) {
                        btnLove_song.setBackgroundResource(R.drawable.ic_song_hearts_500)
                    } else {
                        btnLove_song.setBackgroundResource(R.drawable.ic_song_heart_500)
                    }
                } else {
                    btnLove_song.visibility = View.INVISIBLE
                }
                //更新模式
                if (muBinder.setIsOrder()) {
                    btnMode_song.setBackgroundResource(R.drawable.ic_song_order_100)
                } else {
                    btnMode_song.setBackgroundResource(R.drawable.ic_song_loop_100)
                }
            }
            myHandler.postDelayed(this, 200)
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_song)
        myLog("$mTAG: onCreate")
        this@SongActivity.topBar_song.showBtn(false)
        //接收数据
        val bundle = intent.extras
        sorts = bundle?.getString("_sort")
        index = bundle?.getInt("_pos")
        myLog("$mTAG: sorts=$sorts index=$index")
        //启动Service
        Intent(this@SongActivity, MusicService::class.java).apply {
            putExtra("sorts", sorts)
            putExtra("index", index)
            startService(this)
            bindService(this, muConnection, Context.BIND_AUTO_CREATE)
        }
        //按钮监听
        btnPlayOrPause_song.setOnClickListener(this)
        btnLove_song.setOnClickListener(this)
        btnMode_song.setOnClickListener(this)
        txtMsg_song.setOnClickListener(this)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onNewIntent(intent: Intent) {
        val lov = intent.getStringExtra("_sort")
        val pos = intent.getIntExtra("_pos", -2)
        myLog("$mTAG: onNewIntent lov=$lov pos=$pos")
        if ((lov != sorts || pos != index) && lov != null) {
            sorts = lov
            index = pos
            muBinder!!.setNewInit(sorts!!, index!!)
        }else{
            myLog("$mTAG: old sorts=$sorts index=$index")
        }
        super.onNewIntent(intent)
    }

    override fun onClick(v: View?) {
        muBinder?.let { muBinder ->
            when (v?.id) {
                //接收service时长
                R.id.btnPlayOrPause_song -> {
                    muBinder.setPlayOrPause()
                }
                R.id.btnLove_song -> {
                    muBinder.setLike()
                }
                R.id.btnMode_song -> {
                    muBinder.setOrder()
                }
                R.id.btnLast_song -> {
                    muBinder.setLast()
                }
                R.id.btnNext_song -> {
                    muBinder.setNext()
                }
                R.id.txtMsg_song -> {
                    /*supportFragmentManager.beginTransaction()
                        .add(R.id.layoutFraMsg_song, SongMsgFragment()).commit()*/
                    Intent(this, OptionActivity::class.java).apply {
                        putExtra("_option", "op_songMsg")
                        startActivity(this)
                    }
                }
                else -> {
                    myLog("$mTAG: view=${v?.id}")
                }
            }
        }
    }

    override fun onDestroy() {
        myLog("$mTAG: onDestroy")
        super.onDestroy()
        myHandler.removeCallbacks(myRunnable)
        val intentService = Intent(this@SongActivity, MusicService::class.java)
        stopService(intentService)
        unbindService(muConnection)
    }

    //防止按下返回键后播放活动结束
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /*supportFragmentManager.beginTransaction()
                .remove(SongMsgFragment()).commit()*/
            //myLog("$mTAG: fragment=${supportFragmentManager.fragments}")
            moveTaskToBack(false)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}